import { connect } from 'dva';
import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { Table, Button, Card, Col, Row, Radio, Select } from 'antd';

import { fieldsToParams, createPageConfig, radioOptions, selectOptions } from 'src/utils/transform';
import { systemConstants } from 'src/utils/constants';
import AppInfoCard from 'src/components/biz/AppInfoCard';
import IndexInfoCard from 'src/components/biz/IndexInfoCard';

import FilterForm from './filterForm';
import Detail from './detail';
import ListCURDCreator from '../creator/list';

const RadioGroup = Radio.Group;

function List({ dispatch, control: moduleModel }) {

  const { moduleName } = moduleModel;
  const basePayload = { module: moduleName };

  const { filteredList: list, toDetail, cancelSubmit } = ListCURDCreator(moduleModel, dispatch);

  function search(fields) {
    const { range, status } = fieldsToParams(fields);
    let params = {};
    if (+status !== -1) {
      params.status = status;
    }
    if (range) {
      params.beginDate = range[0].startOf('day').format(systemConstants.dateFormat.backEnd);
      params.endDate = range[1].endOf('day').format(systemConstants.dateFormat.backEnd);
    }

    list({ ...params });
  }

  function onControlTypeChange(e) {
     dispatch({ type: moduleName + '/controlTypeChange', payload: e.target.value });
  }

  function doImport() {
    let { controlType, importedDatasource, relatedData } = moduleModel;
    let payload = { indexId: relatedData.indexData.id };
    if (controlType !== '0') {
      payload.datasourceId = importedDatasource;

    }
    dispatch({ type: moduleName + '/doImport', payload });
  }

  function onDatasourceChange(value) {
    dispatch({ type: moduleName + '/datasourceChange', payload: value });
  }

  const paginationInfo = createPageConfig(moduleModel, list);

  const { searchParams, fieldErrors, relatedData } = moduleModel;
  const { appData, indexData, datasourceList } = relatedData;

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      width: 70,
    },
    {
      title: '粒度',
      dataIndex: 'runType',
      key: 'runType',
      width: 70,
      render: value => systemConstants.control.runType[value],
    },
    {
      title: '类型',
      dataIndex: 'indexBuildType',
      key: 'indexBuildType',
      width: 70,
      render: value => systemConstants.control.indexBuildType[value],
    },
    {
      title: '方式',
      dataIndex: 'gradingType',
      key: 'gradingType',
      width: 70,
      render: value => systemConstants.control.gradingType[value],
    },
    {
      title: '时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 70,
      render: value => systemConstants.control.status[value],
    },
    {
      title: '操作',
      width: 120,
      key: 'action',
      render: (text, item) => (
        <div>
          <span><a href="javascript:;" onClick={toDetail} id={`detailId_${item.id}`}>详情</a></span>
        </div>
      ),
    }
  ];

  const commonCardConfig = {
    bordered: false,
  };

  const appCardConfig = {
    ...commonCardConfig,
    title: <div><Row>
        <Col span="20">{appData.name}项目信息</Col>
      </Row></div>,
  };

  const indexCardConfig = {
    ...commonCardConfig,
    title: <div><Row>
        <Col span="20">{indexData.name}索引信息</Col>
      </Row></div>,
  };

  const controlTypes = radioOptions(systemConstants.control.runType);
  const datasource = selectOptions(datasourceList, { key: 'id', value: 'name' });

  return (
    <div>
      <Row style={{ marginBottom: '20px' }}>
        <Col span="11">
          <Card  {...appCardConfig}>
            <AppInfoCard data={appData}/>
          </Card>
        </Col>
        <Col span="2"></Col>
        <Col span="11">
          <Card {...indexCardConfig}>
            <IndexInfoCard data={indexData}/>
          </Card>
        </Col>
      </Row>
      <Row style={{ marginBottom: '20px' }}>
        <Col span="24">
          <Card title={ '索引导入' } {...commonCardConfig}>
            <RadioGroup onChange={ onControlTypeChange } value={ moduleModel.controlType } options={ controlTypes } />
            <Select placeholder="选择一个数据源" onChange={ onDatasourceChange }
              style={ moduleModel.datasourceSelectStyle }>{ datasource }</Select>
            <Button onClick={ doImport } type="primary" style={{ marginLeft: '12px' }}>执行导入</Button>
          </Card>
        </Col>
      </Row>
      <Row style={{ marginBottom: '20px' }}>
        <Col span="24">
          <Card title={ '调度历史' } {...commonCardConfig}>
            <div className="query-form">
              <FilterForm
                {...searchParams}
                onSubmit={search}
                fieldErrors={fieldErrors}
                autoSubmit
              />
            </div>
            <div className="query-result">
              <div>
                <Table size="middle" columns={columns} dataSource={moduleModel.list} pagination={paginationInfo} />
              </div>
            </div>
          </Card>
        </Col>
      </Row>
      <Detail
        {...moduleModel}
        visible={ moduleModel.showDetailModal }
        title={ '调度详情' }
        onCancel= {cancelSubmit}
      />
    </div>
  );
}

List.propTypes = {
  dispatch: PropTypes.func.isRequired,
  control: PropTypes.object.isRequired,
};

export default connect(({ control }) => ({ control }))(List);
